﻿using System;
using System.Collections.Generic;
using System.Composition;
using System.IO;
using System.Linq;
using Ant.Interface.FileSystems.AppData;

namespace Ant.Interface.Environment.Configuration
{
    internal class ShellSettingsController : IShellSettingsController
    {
        private readonly IAppDataFolder _appDataFolder;
        private readonly IShellSettingsControllerEventHandler _events;

        [ImportingConstructor]
        public ShellSettingsController([Import]IAppDataFolder appDataFolder, [Import]IShellSettingsControllerEventHandler events)
        {
            _appDataFolder = appDataFolder;
            _events = events;
        }

        IEnumerable<ShellSettings> IShellSettingsController.LoadSettings()
        {
            return LoadSettings().ToArray();
        }

        void IShellSettingsController.SaveSettings(ShellSettings settings)
        {
            if (settings == null)
                throw new ArgumentException("There are no settings to save.");
            if (string.IsNullOrEmpty(settings.Name))
                throw new ArgumentException("Settings \"Name\" is not set.");

            var filePath = Path.Combine(Path.Combine("Sites", settings.Name), "Settings.txt");
            _appDataFolder.CreateFile(filePath, ShellSettingsSerializer.ComposeSettings(settings));
            _events.Saved(settings);
        }

        private IEnumerable<ShellSettings> LoadSettings()
        {
            var filePaths = _appDataFolder
                .ListDirectories("Sites")
                .SelectMany(path => _appDataFolder.ListFiles(path))
                .Where(path => string.Equals(Path.GetFileName(path), "Settings.txt", StringComparison.OrdinalIgnoreCase));

            foreach (var filePath in filePaths)
            {
                yield return ShellSettingsSerializer.ParseSettings(_appDataFolder.ReadFile(filePath));
            }
        }
    }
}